package cc.rengu.igas.share.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * RSA证书工厂类
 *
 * @author fuyp
 * @version 1.0.0
 * 增加初始化私钥
 * @date 20200715
 */
public class RSACerFactory {
    /**
     * 证书容器
     */
    private static Map<String, RSACerPlus> rsaCerHolder = new HashMap<String, RSACerPlus>();
    private static RSACerFactory factory;

    /**
     * 禁止外部初始化 私有构造方法
     */
    private RSACerFactory() {
    }

    /**
     * 获取证书工厂实例
     *
     * @return
     */
    public static RSACerFactory getInstance() {
        if (null == factory) {
            factory = new RSACerFactory();
        }
        return factory;
    }

    /**
     * 返回证书密钥
     *
     * @param keyAlias
     * @param rootPath
     * @param passwordRSA
     * @return
     * @throws Exception
     */
    public RSACerPlus init(String keyAlias, String rootPath, String passwordRSA) throws Exception {
        FileInputStream fi = null;
        try {
            fi = new FileInputStream(new File(rootPath.concat("key.data")));
            byte rawKeyData[] = new byte[fi.available()];
            fi.read(rawKeyData);
            fi.close();
            DesUtil desUtil = DesUtil.getInstance();
            byte[] decryptedData = desUtil.decrypt(Base64Converter.decode(passwordRSA.replace("+", "<").getBytes("UTF-8")), Base64Converter.decode(rawKeyData), null);
            RSACerPlus msgCer = new RSACerPlus();
            StringTokenizer token = new StringTokenizer(new String(decryptedData, "UTF-8"), "|");
            msgCer.initCer(rootPath, token.nextToken(), token.nextToken(), token.nextToken(), token.nextToken());
            return msgCer;
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != fi) {
                try {
                    fi.close();
                } catch (IOException e) {
                }
            }
        }

    }
}
